package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.utils.StringUtils;

public class RegistActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.pass)
    EditText pass;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.edit_image)
    EditText edit_image;
    @BindView(R.id.code)
    EditText code;
    @BindView(R.id.code_invitation)
    EditText codeInvitation;
    @BindView(R.id.agree)
    CheckBox agree;
    @BindView(R.id.getcode)
    TextView getcode;
    @BindView(R.id.code_image)
    WebView code_image;
    @BindView(R.id.regist)
    Button regist;
    private PressenterImpl pressenter;


    private boolean isphone = false;
    private boolean iscode = false;
    private boolean ispass = false;

    private Drawable drawables;


    int beans=0;

    private int djs=60;
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            djs--;
            if (djs<=0){
                getcode.setText("重新获取验证码");
                getcode.setClickable(true);
            }else {
                getcode.setText(djs+"s后重新获取");
                handler.sendEmptyMessageDelayed(0,1000);
            }
        }
    };


    @Override
    protected int getLayout() {
        return R.layout.activity_regist;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        ButterKnife.bind(this);

//        code_image.setImageURI("http://hrk.donghemei.com/appapi/treat/verify_test.html");

        pressenter=new PressenterImpl();
        pressenter.attachView(this);

        code_image.loadUrl(Constant.PATH+"appapi/treat/verify_test.html");
        code_image.setVerticalScrollBarEnabled(false);

        pass.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = pass.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null) {
                    return false;
                }
                //如果不是按下事件，不再处理
                if (motionEvent.getAction() != MotionEvent.ACTION_UP) {
                    return false;
                }
                if (motionEvent.getX() > pass.getWidth() - pass.getPaddingRight() - drawable.getIntrinsicWidth()) {
                    showOrHide(pass);
                }
                return false;
            }
        });

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = phone.getText().toString();
                if (iscode && ispass) {
                    if (s == null || s.equals("")) {
                        isphone=false;
                        regist.setBackgroundResource(R.drawable.back_registn);
                    }else {
                        isphone=true;
                        regist.setBackgroundResource(R.drawable.shape_login);
                    }
                }else {
                    if (s == null || s.equals("")) {
                        isphone=false;
                    }else {
                        isphone=true;
                    }
                    regist.setBackgroundResource(R.drawable.back_registn);
                }
            }
        });

        code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = code.getText().toString();
                if (isphone && ispass) {
                    if (s == null || s.equals("")) {
                        iscode=false;
                        regist.setBackgroundResource(R.drawable.back_registn);
                    }else {
                        iscode=true;
                        regist.setBackgroundResource(R.drawable.shape_login);
                    }
                }else {
                    if (s == null || s.equals("")) {
                        iscode=false;
                    }else {
                        iscode=true;
                    }
                    regist.setBackgroundResource(R.drawable.back_registn);
                }
            }
        });

        pass.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = pass.getText().toString();
                if (isphone && iscode) {
                    if (s == null || s.equals("")) {
                        ispass=false;
                        regist.setBackgroundResource(R.drawable.back_registn);
                    }else {
                        ispass=true;
                        regist.setBackgroundResource(R.drawable.shape_login);
                    }
                }else {
                    if (s == null || s.equals("")) {
                        ispass=false;
                    }else {
                        ispass=true;
                    }
                    regist.setBackgroundResource(R.drawable.back_registn);
                }
            }
        });

    }

    @Override
    protected void initData() {

    }


    private void showOrHide(EditText etPassword) {
        //记住光标开始的位置
        int pos = etPassword.getSelectionStart();
        if (etPassword.getInputType() != (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {//隐藏密码
            drawables = getResources().getDrawable(R.mipmap.eyen);
            drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {//显示密码
            drawables = getResources().getDrawable(R.mipmap.eyes);
            drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
        etPassword.setCompoundDrawablesWithIntrinsicBounds(null,null, drawables, null);
        etPassword.setSelection(pos);
    }


    @OnClick({R.id.back, R.id.getcode,R.id.code_text, R.id.regist, R.id.xieyi, R.id.yinsi})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.code_text:
                code_image.loadUrl(Constant.PATH+"appapi/treat/verify_test.html");
                break;
            case R.id.getcode:

                String phones = phone.getText().toString();
                String edit_images = edit_image.getText().toString();
                if (phones==null||phones.equals("")){
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (edit_images==null||edit_images.equals("")){
                    Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtils.isRegistMobileNO(phones)){
                    Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }

                Map<String,String> map=new HashMap<>();
                map.put("mobile",phones);
                map.put("pictureVerfy",edit_images);
                map.put("token",Constant.TOKEN);
                pressenter.sendMessage(RegistActivity.this, Constant.send_message,map, Bean.class);

                beans = 0;

                break;
            case R.id.regist:


                String phoness = phone.getText().toString();
                String passs = pass.getText().toString();
                String edit_imagess = edit_image.getText().toString();
                String codes = code.getText().toString();
                String codeInvitations = codeInvitation.getText().toString();


                if (phoness==null||phoness.equals("")){
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (passs==null||passs.equals("")){
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (edit_imagess==null||edit_imagess.equals("")){
                    Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (codes==null||codes.equals("")){
                    Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtils.isRegistMobileNO(passs)){
                    Toast.makeText(this, "密码格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtils.isRegistNick(phoness)){
                    Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!agree.isChecked()){
                    Toast.makeText(this, "请阅读并同意采客宝用户协议和隐私政策", Toast.LENGTH_SHORT).show();
                    return;
                }



                beans=1;

                map=new HashMap<>();
                map.put("mobile",phoness);
                map.put("token",Constant.TOKEN);
                map.put("user_pass",passs);
                map.put("pictureVerfy",edit_imagess);
                map.put("code",codes);
                if (codeInvitations!=null&&!codeInvitations.equals("")){
                    map.put("referralCode",codeInvitations);
                }

                pressenter.sendMessage(this,Constant.register,map,Bean.class);
                break;
            case R.id.xieyi:
                intent = new Intent(this, WebActivity.class);
                intent.putExtra("type","1");
                startActivity(intent);
                break;
            case R.id.yinsi:
                intent = new Intent(this, WebActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
                break;
                default:
        }
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof Bean){
            Bean bean= (Bean) data;
            Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
            if (bean.getCode()==1){
                if (beans==0){
                    getcode.setClickable(false);
                    djs=60;
                    handler.sendEmptyMessageDelayed(0,1000);
                }else {
                    finish();
                }
            }else {



                code_image.loadUrl(Constant.PATH+"appapi/treat/verify_test.html");
            }
        }

    }

    @Override
    public void fail(String error) {
        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
    }
}
